package com.ys.store.controller;

import com.ys.store.service.ex.*;
import com.ys.store.util.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

/*控制层类的基类*/
public class BaseController {
    /*操作成功*/
    public static final int OK = 200;

    // 请求处理方法，方法返回值传递给前端的数据
    @ExceptionHandler(ServiceException.class) //用于同一处理抛出的异常，自动将异常对象传递给此方法的参数列表上
    public JsonResult<Void> handleException(Throwable e){
        JsonResult<Void> result = new JsonResult<>(e);
        if(e instanceof UsernameDuplicatedException){
            result.setState(4000);
            result.setMessage("用户名已占用");
        } else if(e instanceof UserNotFoundException){
            result.setState(5001);
            result.setMessage("该用户不存在");
        } else if(e instanceof PasswordNotMatchException){
            result.setState(5002);
            result.setMessage("密码错误");
        } else if(e instanceof InsertException){
            result.setState(5000);
            result.setMessage("注册时产生未知的异常");
        } else if(e instanceof UpdateException){
            result.setState(5003);
            result.setMessage("更新数据时产生异常");
        }
        return result;
    }

    /*获取session对象的uid*/
    public final Integer getuidFromSession(HttpSession session){
        return Integer.valueOf(session.getAttribute("uid").toString());
    }

    /*获取session对象的username*/
    public final String getUsernameFromSession(HttpSession session){
        return session.getAttribute("username").toString();
    }

}
